;
(function (call) {
    var main = {
        userInfo: null,
        areaData: [],
        lon: [],
        lat: [],
        qbTime: '',
        curClass: '',
        init: function () {
            this.initView();
            this.bindEvt();
        },
        initView: function () {
            var userInfo = $("#userInfo").data('info');
            this.userInfo = userInfo;
            this.getAreaData();
        },
        getAreaData: function () {
            var that = this;
            $.getJSON(api.internal.sxsyb.queryHourYbStation, { stationType: '1' }, function (res) {
                if (!res.isSuccess || !res.data) return;
                var lon = [], lat = []
                for (var i = 0; i < res.data.length; i++) {
                    lon.push(res.data[i].lon);
                    lat.push(res.data[i].lat);
                }
                that.areaData = res.data
                that.lon = lon
                that.lat = lat
                that.getFore3hProductDetail(res.data, lon, lat)
            })
        },
        getParams: function () {
            var productInfo = $(".task-menu-list li.active").data('product');
            var time = productInfo.fortime
            var period = time.split(':')[0];
            var qbHours = 8;
            var currentDate = new Date();
            currentDate.setHours(currentDate.getHours() - 24);
            var fcstTime = currentDate.format('yyyyMMdd200000');
            var startPeriod = Number(period) - qbHours + 12;
            var endPeriod = startPeriod + 6;
            if (time == '17:00' || time == '20:00' || time == '23:00') {
                qbHours = 20;
                startPeriod = Number(period) - qbHours + 24;
                endPeriod = startPeriod + 6;
            }
            var params = {
                fcstTime: fcstTime,
                element: 'TMAX,TMIN,EDA,RHMAX,TP,WEA',
                startPeriod: startPeriod,
                endPeriod: endPeriod,
                interval: 3,
                count: 0,
                stationType: 0
            }
            return params;
        },
        getSxsybData: function (sxsybData, lon, lat) {
            var that = this;
            var $body1 = $("#rainfallTable1 tbody").empty();
            var $body2 = $("#rainfallTable2 tbody").empty();
            var params = that.getParams();
            params.lon = lon.join(',');
            params.lat = lat.join(',');
            loading.add('.cafe-container');

            $.getJSON(api.external.getGdybDataByParamData, params, function (res) {
                loading.remove();
                if (!res.success || !res.resultData) return;
                var resultData = res.resultData
                for (var i = 0; i < sxsybData.length; i++) {
                    var dataObj = sxsybData[i];
                    var msg = sxsybData[i].lon + '_' + sxsybData[i].lat;
                    var tmin = resultData[msg]['TMIN'][0][0] == '9999' ? '--' : resultData[msg]['TMIN'][0][0];
                    var tmax = resultData[msg]['TMAX'][0][0] == '9999' ? '--' : resultData[msg]['TMAX'][0][0];
                    var wea = weatherUtil.getText(resultData[msg]['WEA'][0][0]),
                        wea2 = weatherUtil.getText(resultData[msg]['WEA'][0][1]);
                    var $tr = $(`<tr>
                    <td><input type="hidden" value="${dataObj.stationName}">${dataObj.stationName}</td>
                    <td><input type="text" class="wea" title="${resultData[msg]['WEA'][0][0]}" value="${resultData[msg]['WEA'][0][0]}"></td>
                    <td><input type="text" class="wd" value="${resultData[msg]['EDA'][2][0]}"></td>
                    <td><input type="text" class="ws" value="${resultData[msg]['EDA'][3][0]}"></td>
                    <td><input type="text" class="tmax" value="${tmin}~${tmax}"></td>
                    <td><input type="text" class="rh" value="${resultData[msg]['RHMAX'][0][0] == '9999' ? '--' : Math.round(resultData[msg]['RHMAX'][0][0])}%"></td>
                    <td><input type="text" class="rainchance" value="${weatherUtil.getVal(resultData[msg]['WEA'][0][0])}"></td>
                    <td><input type="text" class="tp" value="${resultData[msg]['TP1H'][0][0]}"></td>
                    <td><input type="text" class="lightchance" value="${(wea.indexOf('雷暴')!= -1 || wea.indexOf('雷电')!= -1) ? '60%' : '0%'}"></td>
                    <td><input type="text" class="zhtq" value="${wea}"></td></tr>
                    `);
                    tmin = resultData[msg]['TMIN'][0][1] == '9999' ? '--' : resultData[msg]['TMIN'][0][1]
                    tmax = resultData[msg]['TMAX'][0][1] == '9999' ? '--' : resultData[msg]['TMAX'][0][1]
                    var $tr2 = $(`<tr>
                    <td><input type="hidden" value="${dataObj.stationName}">${dataObj.stationName}</td>
                    <td><input type="text" class="wea" title="${resultData[msg]['WEA'][0][1]}" value="${resultData[msg]['WEA'][0][1]}"></td>
                    <td><input type="text" class="wd" value="${resultData[msg]['EDA'][2][1]}"></td>
                    <td><input type="text" class="ws" value="${resultData[msg]['EDA'][3][1]}"></td>
                    <td><input type="text" class="tmax" value="${tmin}~${tmax}"></td>
                    <td><input type="text" class="rh" value="${resultData[msg]['RHMAX'][0][1] == '9999' ? '--' : Math.round(resultData[msg]['RHMAX'][0][1])}%"></td>
                    <td><input type="text" class="rainchance" value="${weatherUtil.getVal(resultData[msg]['WEA'][0][1])}"></td>
                    <td><input type="text" class="tp" value="${resultData[msg]['TP1H'][0][1]}"></td>
                    <td><input type="text" class="lightchance" value="${(wea2.indexOf('雷暴')!= -1||wea2.indexOf('雷电')!= -1) ? '60%' : '0%'}"></td>
                    <td><input type="text" class="zhtq" value="${wea2}"></td></tr>
                    `);
                    $body1.append($tr);
                    $body2.append($tr2);
                }
            })
        },
        getSxsybData2: function (sxsybData, lon, lat) {
            var that = this;
            var $body = $("#rainfallTable3 tbody").empty();
            var params = that.getParams();
            params.lon = lon.join(',')
            params.lat = lat.join(',')
            params.startPeriod = params.endPeriod;
            params.endPeriod += 6;
            params.interval = 6;
            loading.add('.cafe-container');
            $.getJSON(api.external.getGdybDataByParamData, params, function (res) {
                loading.remove();
                if (!res.success || !res.resultData) return;
                var resultData = res.resultData;
                for (var i = 0; i < sxsybData.length; i++) {
                    var dataObj = sxsybData[i];
                    var msg = sxsybData[i].lon + '_' + sxsybData[i].lat;
                    var $tr = $(`<tr>
                        <td><input type="hidden" value="${dataObj.stationName}">${dataObj.stationName}</td>
                        <td><input type="text" class="wea" value="${resultData[msg]['WEA'][0][0] || '无'}"></td></tr>
                        `);
                    $body.append($tr);
                }
            })
        },
        publishSxsybData: function () {
            var that = this;
            var productInfo = $(".task-menu-list li.active").data('product');
            var hours = productInfo.fortime
            var qbTime = new Date().format('yyyy-MM-dd ' + hours + ':00')
            that.qbTime = qbTime
            var data0_3 = [], data3_6 = [], data6_12 = [];
            $("#rainfallTable1 tbody tr").each(function (i, tr) {
                var str = '';
                $(tr).find('input').each(function (j, input) {
                    str = str + ',' + ($(input).val() || '无');
                })
                str = str.substr(1)
                data0_3.push(str)
            })
            $("#rainfallTable2 tbody tr").each(function (i, tr) {
                var str = '';
                $(tr).find('input').each(function (j, input) {
                    str = str + ',' + ($(input).val() || '无');
                })
                str = str.substr(1)
                data3_6.push(str)
            })
            $("#rainfallTable3 tbody tr").each(function (i, tr) {
                var str = '';
                $(tr).find('input').each(function (j, input) {
                    str = str + ',' + ($(input).val() || '无');
                })
                str = str.substr(1)
                data6_12.push(str)
            })
            var params = {
                userName: that.userInfo.smuser.name,
                productId: productInfo.productId,
                qbTime: qbTime,
                data0_3: data0_3,
                data3_6: data3_6,
                data6_12: data6_12,
				taskId: productInfo.taskId,
				userId:that.userInfo.smuser.iid
            }
            $.ajax({
                url: api.internal.sxsyb.publishSxsyb,
                type: "POST",
                contentType: "application/json;charset=utf-8",
                dataType: 'json',
                data: JSON.stringify(params),
                success: function (res) {
                    if (res.isSuccess) {
                        alert("发布成功");
                        CafeJS.menuFunc.setTask();
                        that.getAreaData();
                    } else {
                        alert("发布失败");
                    }
                },
            })
        },
        getFore3hProductDetail: function (sxsybData, lon, lat) {
            var that = this;
            var productInfo = $(".task-menu-list li.active").data('product');
            var qbTime = productInfo.fortime;
            qbTime = new Date().format('yyyy-MM-dd') + ' ' + qbTime;
            qbTime = new Date(qbTime);
            $(".year").val(new Date().format('yyyy年MM月dd日'));
            $(".hours1").val(new Date(qbTime).format('hh时'));
            $("#time1").find('.hours2').val(qbTime.format('hh时'))
            var hours1 = qbTime.setHours(qbTime.getHours() + 3);
            $("#time1").find('.hours3').val(new Date(hours1).format('hh时'))
            $("#time2").find('.hours2').val(new Date(hours1).format('hh时'))
            var hours2 = qbTime.setHours(qbTime.getHours() + 3);
            $("#time2").find('.hours3').val(new Date(hours2).format('hh时'))
            $("#time3").find('.hours2').val(new Date(hours2).format('hh时'))
            var hours3 = qbTime.setHours(qbTime.getHours() + 6);
            $("#time3").find('.hours3').val(new Date(hours3).format('hh时'))
            var hours = productInfo.fortime;
            var queryTime = new Date().format('yyyy-MM-dd ' + hours + ':00')
            $.getJSON(api.internal.sxsyb.getFore3hProductDetail, { queryTime: queryTime }, function (res) {
                if (!res.isSuccess) return;
                if (JSON.stringify(res.data) == "{}") {
                    that.getSxsybData(sxsybData, lon, lat);
                    that.getSxsybData2(sxsybData, lon, lat);
                } else {
                    that.initSxsybData(sxsybData, res.data);
                }
            })
        },
        initSxsybData: function (sxsybData, data) {
            $("#txt3").text(data.txt00_03)
            $("#txt6").text(data.txt03_06)
            $("#txt12").text(data.txt06_12)
            $(".rainfall_tab li.path3").data("path", data.path00_03)
            $(".rainfall_tab li.path6").data("path", data.path03_06)
            $(".rainfall_tab li.path12").data("path", data.path06_12)
            var $body1 = $("#rainfallTable1 tbody").empty();
            var $body2 = $("#rainfallTable2 tbody").empty();
            var $body3 = $("#rainfallTable3 tbody").empty();
            for (var i = 0; i < sxsybData.length; i++) {
                var dataObj = sxsybData[i];
                var msg = sxsybData[i].lon.toFixed(2) + '_' + sxsybData[i].lat.toFixed(2)
                var $tr = $(`<tr>
                <td><input type="hidden" value="${dataObj.stationName}">${dataObj.stationName}</td>
                <td><input type="text" class="wea" title="${data.txt00_03Data[msg].WEA}" value="${data.txt00_03Data[msg].WEA}"></td>
                <td><input type="text" class="wd" value="${data.txt00_03Data[msg].WD}"></td>
                <td><input type="text" class="ws" value="${data.txt00_03Data[msg].WS}"></input></td>
                <td><input type="text" class="tmax" value="${data.txt00_03Data[msg].T}"></td>
                <td><input type="text" class="rh" value="${data.txt00_03Data[msg].RH}"></td>
                <td><input type="text" class="rainchance" value="${data.txt00_03Data[msg].TPGL}"></td>
                <td><input type="text" class="tp" value="${data.txt00_03Data[msg].TP}"></td>
                <td><input type="text" class="lightchance" value="${data.txt00_03Data[msg].LIGHT}"></td>
                <td><input type="text" class="zhtq" value="${data.txt00_03Data[msg].ZHTQ}"></td></tr>
                `);
                var $tr2 = $(`<tr>
                <td><input type="hidden" value="${dataObj.stationName}">${dataObj.stationName}</td>
                <td><input type="text" class="wea" title="${data.txt03_06Data[msg].WEA}" value="${data.txt03_06Data[msg].WEA}"></td>
                <td><input type="text" class="wd" value="${data.txt03_06Data[msg].WD}"></td>
                <td><input type="text" class="ws" value="${data.txt03_06Data[msg].WS}"></td>
                <td><input type="text" class="tmax" value="${data.txt03_06Data[msg].T}"></td>
                <td><input type="text" class="rh" value="${data.txt03_06Data[msg].RH}"></td>
                <td><input type="text" class="rainchance" value="${data.txt03_06Data[msg].TPGL}"></td>
                <td><input type="text" class="tp" value="${data.txt03_06Data[msg].TP}"></td>
                <td><input type="text" class="lightchance" value="${data.txt03_06Data[msg].LIGHT}"></td>
                <td><input type="text" class="zhtq" value="${data.txt03_06Data[msg].ZHTQ}"></td></tr>
                `);
                var $tr3 = $(`<tr>
                        <td><input type="hidden" value="${dataObj.stationName}">${dataObj.stationName}</td>
                        <td><input type="text" class="wea" title="${data.txt06_12Data[msg].WEA}" value="${data.txt06_12Data[msg].WEA || '无'}"></td></tr>
                        `);
                $body1.append($tr);
                $body2.append($tr2);
                $body3.append($tr3);
            }
        },
        sxsybdownLoad: function (path) {
            var url = api.internal.common.downLoadFile + '?path=' + path
            $("#sxsybTxt").attr('src', url)
        },
        // 批量编辑弹框
        editPop: function (curClass, offset) {
            $(".edit_pop").remove();
            if (curClass == 'ws' || curClass == 'tmax' || curClass == 'rh' || curClass == 'rainchance' || curClass == 'tp' || curClass == 'lightchance') {
                var $div = $('<div>').addClass('edit_pop').css({
                    left: offset.left - 138,
                    top: offset.top
                });
                var list = '<div class="edit_pop_head"><i class="edit_close">×</i></div>'
                list += '<div class="edit_pop_body"><input type="number" value="1" class="edit_input1">'
                if (curClass == 'ws' || curClass == 'tmax') {
                    list += '<div>~</div><input type="number" value="1" class="edit_input2">'
                    $div.css('width', '200px');
                }
                list += '<div class="oper_div"><span class="jia">+</span><span class="jian">-</span><span class="equal">=</span></div></div>'
                var $list = $(list);
                $(".rainfall").append($div.append($list));
            }
        },
        bindEvt: function () {
            var that = this;
            $(".remake_opr").click(function () {
                that.getSxsybData(that.areaData, that.lon, that.lat)
                that.getSxsybData2(that.areaData, that.lon, that.lat)
            })
            $(".publish_opr").click(function () {
                that.publishSxsybData();
            })
            $(".rainfall_table tbody").on('change', '.wea', function () {
                var val = $(this).val();
                if (val.indexOf('雷暴') != -1 || val.indexOf('雷电') != -1) {
                    $(this).parent().siblings().find('.lightchance').val('60%');
                } else {
                    $(this).parent().siblings().find('.lightchance').val('0%');
                }
                $(this).parent().siblings().find('.rainchance').val(weatherUtil.getVal(val));
                $(this).parent().siblings().find('.zhtq').val(weatherUtil.getText(val));
            }).bind('contextmenu', function () {
                return false;
            }).on('mousedown', 'input', function (e) {
                $(".edit_pop").remove();
                var curClass = $(this).attr('class').split(' ')[0], offset = $(this).offset();
                that.curClass = curClass;
                if (e.which == 3) {
                    $(this).addClass('active').closest('div').find('.' + curClass).addClass('active');
                    $(this).closest('div').find('.' + curClass).parent().siblings().find('input').removeClass('active');
                    that.editPop(curClass, offset);
                } else {
                    $(this).closest('div').find('.' + curClass).parent().siblings().find('input').removeClass('active');
                }
            }).on('change', 'input', function (e) {
                var curClass = $(this).attr('class').split(' ')[0], val = $(this).val();
                if (curClass == 'wd' || curClass == 'zhtq' || curClass == 'wea') {
                    $(this).closest('tr').siblings().find('.active').val(val);
                }
                if (curClass == 'wea') {
                    $('.active').parent().siblings().find('.rainchance').val(weatherUtil.getVal(val));
                }
            }).on('blur', 'input', function (e) {
                var curClass = $(this).attr('class').split(' ')[0];
                if (curClass == 'ws' || curClass == 'tmax' || curClass == 'rh' || curClass == 'rainchance' || curClass == 'tp' || curClass == 'lightchance') return;
                $(this).removeClass('active').closest('tr').siblings().find('.' + curClass).removeClass('active');
            })
            $(".rainfall_tab li").click(function () {
                $(this).addClass("active").siblings().removeClass("active");
                $(".rainfall_data>li").eq($(this).index()).show().siblings().hide();
            })
            $("#downLoadBtn").click(function () {
                var path = $(".rainfall_tab li.active").data('path');
                that.sxsybdownLoad(path);
            })
            $(".rainfall").on('click', '.edit_close', function () {
                $(".edit_pop").remove();
                $(".rainfall_table").find('input').removeClass('active');
            }).on('click', '.jia', function () {
                var val1 = $('.edit_input1').val(), val2 = $('.edit_input2').val();
                if (that.curClass == 'ws') {
                    $(".rainfall_table tr").find('input.active').each(function (i, item) {
                        var itemVal = $(item).val();
                        var v1 = itemVal.split('-')[0], v2 = itemVal.split('-')[1].split('级')[0];
                        var total = (Number(v1) + Number(val1)) + '-' + (Number(v2) + Number(val2));
                        $(item).val(total + '级')
                    })
                } else if (that.curClass == 'tmax') {
                    $(".rainfall_table tr").find('input.active').each(function (i, item) {
                        var itemVal = $(item).val();
                        var v1 = itemVal.split('~')[0], v2 = itemVal.split('~')[1];
                        var total = (Number(v1) + Number(val1)) + '~' + (Number(v2) + Number(val2));
                        $(item).val(total)
                    })
                } else if (that.curClass == 'tp') {
                    $(".rainfall_table tr").find('input.active').each(function (i, item) {
                        var total = (Number($(item).val()) + Number(val1))
                        $(item).val(total)
                    })
                } else {
                    $(".rainfall_table tr").find('input.active').each(function (i, item) {
                        var total = (Number($(item).val().replace('%', '')) + Number(val1))
                        $(item).val(total + '%')
                    })
                }
            }).on('click', '.jian', function () {
                var val1 = $('.edit_input1').val(), val2 = $('.edit_input2').val();
                if (that.curClass == 'ws') {
                    $(".rainfall_table tr").find('input.active').each(function (i, item) {
                        var itemVal = $(item).val();
                        var v1 = itemVal.split('-')[0], v2 = itemVal.split('-')[1].split('级')[0];
                        if (v1 == '0') return;
                        var total = (Number(v1) - Number(val1)) + '-' + (Number(v2) - Number(val2));
                        $(item).val(total + '级')
                    })
                } else if (that.curClass == 'tmax') {
                    $(".rainfall_table tr").find('input.active').each(function (i, item) {
                        var itemVal = $(item).val();
                        var v1 = itemVal.split('~')[0], v2 = itemVal.split('~')[1];
                        var total = (Number(v1) - Number(val1)) + '~' + (Number(v2) - Number(val2));
                        $(item).val(total)
                    })
                } else if (that.curClass == 'tp') {
                    $(".rainfall_table tr").find('input.active').each(function (i, item) {
                        var total = (Number($(item).val()) - Number(val1))
                        $(item).val(total)
                    })
                } else {
                    $(".rainfall_table tr").find('input.active').each(function (i, item) {
                        var total = (Number($(item).val().replace('%', '')) - Number(val1))
                        $(item).val(total + '%')
                    })
                }
            }).on('click', '.equal', function () {
                var val1 = $('.edit_input1').val(), val2 = $('.edit_input2').val();
                if (that.curClass == 'ws') {
                    var total = (val1 + '-' + val2);
                    $(".rainfall_table").find('.active').val(total + '级');
                } else if (that.curClass == 'tmax') {
                    var total = (val1 + '~' + val2);
                    $(".rainfall_table").find('.active').val(total);
                } else if (that.curClass == 'tp') {
                    $(".rainfall_table").find('.active').val(val1);
                } else {
                    $(".rainfall_table").find('.active').val(val1 + '%');
                }
            })
        },
    };
    if (typeof call === 'function') {
        call(main);
    }
})(function (main) {
    main.init();
})